//@auther foolbread
//@time 2016-03-09
//@file ApnsHttp2/apns/apns_manager.go
package apns

import (
	"ApnsHttp2/config"
	"ApnsHttp2/error"
	"ApnsHttp2/statics"
	"github.com/foolbread/fbcommon/golog"
)

func InitApns() {
	golog.Info("initing ApnsHttp2 apns...")
	g_manager = newApnsManager()
}

func GetApns() *apnsManager {
	return g_manager
}

var g_manager *apnsManager

type apnsManager struct {
	apnsCliMap map[int][]*apnsClient
}

func newApnsManager() *apnsManager {
	am := new(apnsManager)
	am.apnsCliMap = make(map[int][]*apnsClient)

	infos := config.GetConfigInstance().GetCertificateInfos()
	for k, v := range infos {
		var c []*apnsClient
		for i := 0; i < v.Count; i++ {
			c = append(c, newApnsClient(v))
		}

		am.apnsCliMap[k] = c
	}

	return am
}

func (a *apnsManager) PushMsg(m *ApnsMessage, f func(*ApnsMessage, int)) {
	clis, ok := a.apnsCliMap[m.M.Type]
	if !ok {
		golog.Error("unknow type:", m.M.Type, "sn:", m.M.Sn, "token:", m.M.Token)
		f(m, error.FORMATERR_STATUS)
		return
	}

	statics.CommitMsgStatics(m.M.Type)

	cli := clis[int(m.Uid[0])%len(clis)]

	cli.pushNotification(m, f)
}
